﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jungle.Code.BLL;
using Jungle.Code.Core;
using Jungle.Code.Utils;
using System.Collections.Generic;
using Jungle.Code.DAL;
using System.Data.SqlClient;

using Jungle.Users;

public partial class RegisterUser : UserControl
{
    protected override void OnInit(EventArgs e)
    {
        DataSet cds = UserManager.GetCountrys();
        ddl_country.Items.Clear();
        for (int i = 0; i < cds.Tables[0].Rows.Count; i++)
        {
            ddl_country.Items.Add(new ListItem(cds.Tables[0].Rows[i][1].ToString(), cds.Tables[0].Rows[i][0].ToString()));
        }

        foreach (ListItem l in UserManager.ddl_Roles().Items) { ddl_Roles.Items.Add(l); }

        if(Request["cmd"] != null)
            if (Request["cmd"] == "edit")
            {
                lb_0001.Text = "Редактирование данных пользователя";
                LoadUserData();
            }

        try
        {
            Activation();
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }
        base.OnInit(e);
    }
    // ---------------------------------------------------------------------------------------
    public void LoadUserData()
    {
        if (Request["id"] != null)
        {
            UserManager us = new UserManager();
            us.UserId = Convert.ToInt32(Request["id"]);
            us.GetById();

            tb_Name.Text = us.Name;
            tb_Fname.Text = us.Fname;
            tb_Email.Text = us.Email;
            ddl_country.Items.FindByValue(us.Country.ToString()).Selected = true;
            ddl_Roles.Items.FindByValue(us.RoleId.ToString()).Selected = true;
            tb_Phone.Text = us.Phone;
            if (us.Photo.Length > 0)
            {
                img_Photo.Visible = true;
                img_Photo.ImageUrl = UrlHelper.GetSiteUrl() + us.Photo;
            }
            tb_City.Text = us.City;

            btn_Registr.Visible = false;
            btn_Edit.Visible = true;
        }
    }
    // ---------------------------------------------------------------------------------------
    protected void Edit(object sender, EventArgs e)
    {
        try
        {
            UserManager um = new UserManager();
            um.UserId = Convert.ToInt32(Request["id"]);
            um.GetById();

            bool valid = true;
            ValidBlock.InnerHtml = "";

            if (tb_Name.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите имя<br/>"; }
            if (tb_Fname.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите фамилию<br/>"; }
            if (tb_Email.Text.Trim().Length < 1 || tb_Email.Text.IndexOf("@") == -1) { valid = false; ValidBlock.InnerHtml += "Укажите Email<br/>"; }
            if (tb_Password.Text.Trim() != tb_Repassword.Text.Trim()) { valid = false; ValidBlock.InnerHtml += "Пароли не совпадают<br/>"; }



            if (valid)
            {
                um.Email = tb_Email.Text.Trim();
                um.Country = Convert.ToInt32(ddl_country.SelectedValue);
                um.City = tb_City.Text;
                um.Name = tb_Name.Text.Trim();
                um.Fname = tb_Fname.Text.Trim();
                um.RegDate = DateTime.Now;
                if (tb_Repassword.Text.Length > 4 && tb_Password.Text.Length > 4) um.Password = UserManager.getMd5Hash(tb_Repassword.Text.Trim());
                if (fu_Photo.HasFile) um.Photo = LoadImg();
                um.Phone = tb_Phone.Text.Trim();
                um.RoleId = Convert.ToInt32(ddl_Roles.SelectedValue);
                um.Update();

            }

            Response.Redirect(UrlHelper.GetAdminUrl() + "Users.aspx");
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }        
    }
    // ---------------------------------------------------------------------------------------
    protected void SendRegisterRequest(object sender, EventArgs e)
    {
        try
        {
            UserManager um = new UserManager();
            bool valid = true;
            ValidBlock.InnerHtml = "";

            um.Email = tb_Email.Text.Trim();
            if (!um.CheckEmail()) { valid = false; ValidBlock.InnerHtml += "Пользователь с таким email уже зарегистрирован<br/>"; }
            if (tb_Name.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите имя<br/>"; }
            if (tb_Fname.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите фамилию<br/>"; }
            if (tb_Email.Text.Trim().Length < 1 || tb_Email.Text.IndexOf("@") == -1) { valid = false; ValidBlock.InnerHtml += "Укажите Email<br/>"; }
            if (tb_Password.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите пароль<br/>"; }
            if (tb_Repassword.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Повторите в пароль<br/>"; }
            if (tb_Password.Text.Trim() != tb_Repassword.Text.Trim()) { valid = false; ValidBlock.InnerHtml += "Пароли не совпадают<br/>"; }



            if (valid)
            {
                um.Email = tb_Email.Text.Trim();
                um.Country = Convert.ToInt32(ddl_country.SelectedValue);
                um.City = tb_City.Text;
                um.Name = tb_Name.Text.Trim();
                um.Fname = tb_Fname.Text.Trim();
                um.RegDate = DateTime.Now; 
                um.Password = tb_Repassword.Text.Trim();
                um.Activation = GetRandom();
                um.Photo = LoadImg();
                um.Phone = tb_Phone.Text.Trim();
                um.RoleId = Convert.ToInt32(ddl_Roles.SelectedValue);
                um.Add();

                UserManager.SendEmail(um.Email, "Alex Consult. Registration Confirm", "Вы были зарегистрированы в проекте Alex Consult. \r\n Для подтверждения перейдите по следующей ссылке: " + UrlHelper.GetAdminUrl() + "Users.aspx?code=" + um.Activation);
                tbl_register.Visible = false;
                lb_Activation.Text = "Now you must activate your user account. We send all need information on your email" + um.err;
            }
        }
        catch(Exception ex)
        {
            GenerateEx(ex);
        }

    }
    // ---------------------------------------------------------------------------------------
    protected void Activation()
    {
        if (Session["mmi"] != null)
        {
            if (Session["mmi"] == "1")
            {
                tbl_register.Visible = false;
                lb_Activation.Text = "Activation sucsess!. We send all need information on your email";
            }
        }
        if (Request["code"] != null)
        {
            try
            {
                tbl_register.Visible = false;
                UserManager um = new UserManager();
                um.Activation = Request["code"];
                um.GetByActivation();
                if (um.Email.Length > 0)
                {
                    um.Activation = "true";
                    um.Update();

                    UserManager.SendEmail(um.Email, "Alex Consult. Wellcome", "Ваш аккаунт был подтвержден. \r\n Для входа используйте следующие данные: \r\n Логин: " + um.Email + "\r\n Пароль: " + um.Password);
                    um.Password = UserManager.getMd5Hash(um.Password.Trim());
                    um.Update();

                    Session["mmi"] = "1";
                    Response.Redirect(UrlHelper.GetAdminUrl() + "Users.aspx");
                }
            }
            catch { }
        }
    }
    // ---------------------------------------------------------------------------------------
    private string GetRandom()
    {
        string str = "";
        string mask = "1234567890qwertyuiopasdfghjklzxcvbnm";
        Random rnd = new Random();
        for (int i = 0; i < 32; i++)
        { 
            str += mask[rnd.Next(0, 30)];
        }
        return str;
    }
    // ---------------------------------------------------------------------------------------
    public string LoadImg()
    {
        string result = "";
        try
        {
            if (fu_Photo.HasFile)
            {
                System.Drawing.Image loadedImg = System.Drawing.Image.FromStream(fu_Photo.PostedFile.InputStream);
                int width = 200;
                if (loadedImg.Width < width)
                    width = loadedImg.Height;

                double d1 = Math.Round((double)loadedImg.Width / width, 4);
                double d2 = Math.Round((double)loadedImg.Height / d1, 4);
                int height = Convert.ToInt32(d2);

                System.Drawing.Image savedImg = loadedImg.GetThumbnailImage(width, height, null, IntPtr.Zero);

                string fname = "/UserFiles/Avatars/" + GetRandom().Substring(0,6) + ".jpg";
                savedImg.Save(Server.MapPath(fname), System.Drawing.Imaging.ImageFormat.Jpeg);

                result = fname;
            }
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }
        return result;
    }
    // ---------------------------------------------------------------------------------------
    protected void GenerateEx(Exception ex)
    {
        Response.Write("<div onclick=\"this.style.display='none';\" class=\"div_err\">Произошла ошибка. <br/> Данные о ней были переданы разработчикам. <br/> Приносим наши извинения за предоставленные неудобства.</div>");
        if (ex.Message.IndexOf("Thread was being") == -1)
        {
            UserManager.SendEmail("t3.s@meta.ua", "Отчет по ошибке Alex Consult", ex.Message.ToString() + "\r\n\r\n" + ex.StackTrace.ToString() + "\r\n\r\n" + ex.Source.ToString());
            //UserManager.SendEmail("akobrinets@gmail.com", "Отчет по ошибке Alex Consult", ex.Message.ToString() + "\r\n\r\n" + ex.StackTrace.ToString() + "\r\n\r\n" + ex.Source.ToString());
        }
    }

}

